package de.velvettear.squirrel.gui;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import de.velvettear.squirrel.R;
import de.velvettear.squirrel.kernel.Statics;
import de.velvettear.squirrel.util.ApplicationHelper;
import de.velvettear.squirrel.util.BitmapHelper;

public class ShortCutFrame extends FragmentActivity implements ActionBar.TabListener {
				
	private static ViewPager viewPager;
	private static SectionsPagerAdapter sectionsPagerAdapter;	
			
	// ShortCutFragment
	private static RadioButton rb_url;
	private static RadioButton rb_app;
	private static EditText et_name;
	private static TextView tv_link;
	private static EditText et_link;
	private static Spinner sp_link;
	private static ImageView iv_icon;
	private static LinearLayout ll_icon;
	private static String icon_path;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_shortcutframe);

		final ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
				
		sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

		viewPager = (ViewPager) findViewById(R.id.pager);
		viewPager.setAdapter(sectionsPagerAdapter);

		viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				actionBar.setSelectedNavigationItem(position);
			}
		});

		for (int i = 0; i < sectionsPagerAdapter.getCount(); i++) {
			actionBar.addTab(actionBar.newTab().setText(sectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
			actionBar.newTab();
		}	
				
	}
			
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {		
		getMenuInflater().inflate(R.menu.menu_shortcutframe, menu);
		return super.onCreateOptionsMenu(menu);	
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
		
		case R.id.menu_shortcutframe_icon:
			resetIcon();
			chooseIcon();	
			break;
			
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
		invalidateOptionsMenu();
		viewPager.setCurrentItem(tab.getPosition());		
	}

	@Override
	public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
		
	}

	@Override
	public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
		
	}
		
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);	
		
		if (requestCode == Statics.REQUEST_FILEEXPLORER) {
			if (resultCode == RESULT_OK) {
				
				String path = getPathFromUri(intent.getData());
				
				File icon = new File(path);
				if (icon.exists() && icon.isFile()) {
					Bitmap bitmap = BitmapHelper.createBitmap(getApplicationContext(), icon.getAbsolutePath());
					if (bitmap == null) {
						Toast.makeText(getApplicationContext(), "Error creating bitmap from file!", Toast.LENGTH_SHORT).show();
						return;
					} else {
						icon_path = icon.getAbsolutePath();
						iv_icon.setImageBitmap(bitmap);
						ll_icon.setVisibility(View.VISIBLE);
					}
					return;
				} else {
					Toast.makeText(getApplicationContext(), "Error creating bitmap from file!", Toast.LENGTH_SHORT).show();
				}
			} else {
				Toast.makeText(getApplicationContext(), "No icon chosen!", Toast.LENGTH_SHORT).show();
			}
		}
	}
			
	private static int getCurrentFragment() {
		return (int) sectionsPagerAdapter.getItemId(viewPager.getCurrentItem());
	}
			
	private String getPathFromUri (Uri contentUri) {
		String path = "";
		android.database.Cursor cursor = null;
		try { 
			String[] proj = { MediaStore.Images.Media.DATA };
			cursor = getApplicationContext().getApplicationContext().getContentResolver().query(contentUri, proj, null, null, null);
			int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		    cursor.moveToFirst();
		    path = cursor.getString(index);
		    cursor.close();
		} catch (Exception e) {
			if (e.getMessage() != null) {
				Log.e("getPathFromUri()", e.getMessage());				
			}				
		}
		return path;
	}
	
	private void resetIcon() {
		ll_icon.setVisibility(View.GONE);
		iv_icon.setImageDrawable(null);
		icon_path = "";
	}
	
	private void chooseIcon() {
		Intent fileExplorerIntent = new Intent(Intent.ACTION_GET_CONTENT);
		fileExplorerIntent.setType("image/*");
		startActivityForResult(fileExplorerIntent, Statics.REQUEST_FILEEXPLORER);	
	}
	
	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			switch (position) {
			
			case 0: return ShortCutFragment.newInstance();
			
			default: return ShortCutFragment.newInstance();
			
			}
		}

		@Override
		public int getCount() {	
			return 1;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			switch (position) {
			case 0:
				return Statics.SHORTCUTS;
			}
			return null;
		}
	}
		
	public static class ShortCutFragment extends Fragment implements OnClickListener, OnCheckedChangeListener {
		
		private static ArrayAdapter<String> adapter = null;
		private static List<ResolveInfo> appList = null;
		private static ResolveInfo selectedApp = null;
		private static String mode;
		
		public ShortCutFragment() {
		
		}

		public static ShortCutFragment newInstance() {
			ShortCutFragment fragment = new ShortCutFragment();
			return fragment;
		}
		
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_shortcuts, container, false);
					
			init(rootView);
			
			return rootView;
		}

		private void init(View rootView) {
			mode = Statics.SHORTCUTS_MODE_URL;
			
			rb_url = (RadioButton) rootView.findViewById(R.id.shortcuts_rb_mode_url);
			rb_app = (RadioButton) rootView.findViewById(R.id.shortcuts_rb_mode_app);
			et_name = (EditText) rootView.findViewById(R.id.shortcuts_et_name);
			tv_link = (TextView) rootView.findViewById(R.id.shortcuts_tv_link);
			et_link = (EditText) rootView.findViewById(R.id.shortcuts_et_link);
			sp_link = (Spinner) rootView.findViewById(R.id.shortcuts_sp_link);
			iv_icon = (ImageView) rootView.findViewById(R.id.shortcuts_iv_icon);
			ll_icon = (LinearLayout) rootView.findViewById(R.id.shortcuts_ll_icon);	
						
			Button btn_create = (Button) rootView.findViewById(R.id.shortcuts_btn_create);
			btn_create.setOnClickListener(this);
						
			rb_url.setOnCheckedChangeListener(this);
			rb_app.setOnCheckedChangeListener(this);
			
			List<String> appNames = new ArrayList<String>();
			for (ResolveInfo info : ApplicationHelper.getApplicationList(getActivity())) {
				appNames.add(info.activityInfo.packageName);
			}
			
			adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, appNames);
			sp_link.setAdapter(adapter);			
		}
		
		private void createShortCut() {
			
			String name = et_name.getText().toString();
			
			String currentMode = "";
			String link = "";
			if (mode.equals(Statics.SHORTCUTS_MODE_URL)) {
				currentMode = "URL";
				link = formatURL(et_link.getText().toString());
			} else if (mode.equals(Statics.SHORTCUTS_MODE_APP)) {
				currentMode = "app";
				link = sp_link.getSelectedItem().toString();
			}
			
			if (name.trim().equals("") || name.trim().length() == 0) {
				Toast.makeText(getActivity(), "In order to create a shortcut a name must be specified!", Toast.LENGTH_SHORT).show();
			} else if (link.trim().equals("") || link.trim().length() == 0) {				
				Toast.makeText(getActivity(), "In order to create a shortcut an " + currentMode + " must be specified!", Toast.LENGTH_SHORT).show();
			} else if (icon_path == null || icon_path.trim().equals("") || icon_path.trim().length() == 0) {
				Toast.makeText(getActivity(), "In order to create a shortcut an icon must be chosen!", Toast.LENGTH_SHORT).show();
			} else {				
				Intent shortCutIntent = null;
				if (mode.equals(Statics.SHORTCUTS_MODE_URL)) {
					shortCutIntent = new Intent(Intent.ACTION_VIEW);
					shortCutIntent.setAction(Intent.ACTION_VIEW);
					shortCutIntent.setData(Uri.parse(link));
				} else if (mode.equals(Statics.SHORTCUTS_MODE_APP)) {
					shortCutIntent = getActivity().getPackageManager().getLaunchIntentForPackage(link);
					shortCutIntent.addCategory(Intent.CATEGORY_LAUNCHER);
					shortCutIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				}
								
				Bitmap bitmap = BitmapHelper.createBitmap(getActivity(), icon_path);
				
				Intent addIntent = new Intent();
				addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortCutIntent);
				addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
				addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON, bitmap);
				addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
				getActivity().getApplicationContext().sendBroadcast(addIntent);
				
				Toast.makeText(getActivity(), "Shortcut " + name + " successfully created!", Toast.LENGTH_SHORT).show();
			}									
		}
		
		private String formatURL(String url) {
			if (!url.startsWith("http://") || !url.startsWith("https://")) {
				url = "http://" + url;
			}
			return url;
		}
				
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			
			case R.id.shortcuts_btn_create:
				createShortCut();
				break;
				
			}			
		}

		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			switch (buttonView.getId()) {
				
			case R.id.shortcuts_rb_mode_url:				
				if (isChecked) {
					mode = Statics.SHORTCUTS_MODE_URL;
					tv_link.setText(R.string.radiobutton_url);
					et_link.setVisibility(View.VISIBLE);
					sp_link.setVisibility(View.GONE);
				}
				break;
				
			case R.id.shortcuts_rb_mode_app:
				if (isChecked) {
					mode = Statics.SHORTCUTS_MODE_APP;
					tv_link.setText(R.string.radiobutton_app);
					et_link.setVisibility(View.GONE);
					sp_link.setVisibility(View.VISIBLE);
				} 
				break;
			
			}			
		}
			
	}	
	
}
